package com.meng.demo1.stresstesting;


import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: menglinggang
 * @Date: 2020-07-22
 * @Time: 下午12:53
 */

public class RunTask implements Runnable {


    private String id;

    private String url;

    private CountDownLatch startDownLatch;

    private CountDownLatch endDownLatch;

    private ConcurrentMap<String, CallResult>  resultMap;

    private OkHttpClient okHttpClient;


    public RunTask(String id, String url, CountDownLatch startDownLatch, CountDownLatch endDownLatch, ConcurrentMap<String, CallResult> resultMap, OkHttpClient okHttpClient) {
        this.id = id;
        this.url = url;
        this.startDownLatch = startDownLatch;
        this.endDownLatch = endDownLatch;
        this.resultMap = resultMap;
        this.okHttpClient = okHttpClient;
    }


    @Override
    public void run() {
        CallResult callResult = new CallResult();
        Request request = new Request.Builder().url(url + "?r=" + UUID.randomUUID().toString()).build();
        Call call = okHttpClient.newCall(request);
        try {
        // 等待其他的线程完成
        startDownLatch.await();

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        Response response = call.execute();
        if (response.code() == 200 )  {
            // 记录完成时间
            long endTime = System.currentTimeMillis();

            callResult.setSuccess(true);
            callResult.setHoldTime(endTime - startTime);
        }
        } catch (IOException e) {
            callResult.setSuccess(false);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            resultMap.put(id, callResult);
            endDownLatch.countDown();
        }
    }
}
